//
//  OppositeTableViewCell.m
//  BaChat
//
//  Created by 刘洋 on 16/6/17.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "OppositeTableViewCell.h"
#import "LocationViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>


#define LabelMaxWidth 200

@interface  OppositeTableViewCell ()<NSURLSessionDownloadDelegate>

@property(nonatomic,retain)BaseImageView *voiceImageView;
@property(nonatomic,retain)BaseImageView *textImageView;
@property(nonatomic,retain)BaseImageView *videoImageView;
@property(nonatomic,retain)BaseLabel *messageLabel;
@property(nonatomic,retain)BaseImageView *iconImage;
@property(nonatomic,retain)BaseImageView *playImage;
@property(nonatomic,retain)BaseLabel *timeLabel;


@end




@implementation OppositeTableViewCell

-(void)dealloc{
    [_timeLabel release];
    [_myMessage release];
    [_textImageView release];
    [_voiceImageView release];
    [_videoImageView release];
    [_messageLabel release];
    [_iconImage release];
    [super dealloc];
}





-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createMessageCell];
    }
    return self;
    
    
}

-(void)createMessageCell{
    
    self.iconImage = [[BaseImageView alloc]init];
    self.iconImage.image = [UIImage imageNamed:@"head"];
    self.iconImage.backgroundColor = [UIColor blueColor];
    [self.contentView addSubview:self.iconImage];
    [_iconImage release];
    
    
    self.voiceImageView = [[BaseImageView alloc]init];
    [self.contentView addSubview:self.voiceImageView];
    [_videoImageView release];
    
    self.textImageView = [[BaseImageView alloc]init];
    [self.contentView addSubview:self.textImageView];
    [_textImageView release];
    
    self.videoImageView = [[BaseImageView alloc]init];
    [self.contentView addSubview:self.videoImageView];
    [_videoImageView release];
    
    
    
    self.messageLabel = [[BaseLabel alloc]init];
//   self.messageLabel.backgroundColor = [UIColor yellowColor];
    [self.contentView addSubview:self.messageLabel];
    [_messageLabel release];
    self.messageLabel.numberOfLines = 0;
    //按文字换行
    self.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.messageLabel.userInteractionEnabled = YES;
    
    //此方法用于播放语音
    UITapGestureRecognizer *tapLabel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(messageLabelTap:)];
    [self.messageLabel addGestureRecognizer:tapLabel];
    
    
    [self.iconImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.width.height.mas_equalTo(40);
        make.left.mas_equalTo(10);
        
        
    }];
    
    
    self.playImage = [[BaseImageView alloc]initWithImage:[UIImage imageNamed:@"play"]];
    [self.contentView addSubview:self.playImage];
    [self.playImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView).offset(100);
        make.top.mas_equalTo(self.contentView).offset(60);
        make.width.height.mas_equalTo(40);
        
    }];
    
    self.timeLabel = [[BaseLabel alloc]init];
    self.timeLabel.backgroundColor = [UIColor lightGrayColor];
     self.timeLabel.font = [UIFont systemFontOfSize:13];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.layer.masksToBounds = YES;
    self.timeLabel.layer.cornerRadius = 2;
    [self.contentView addSubview:self.timeLabel];
    [_timeLabel release];
    
}



-(void)setMyMessage:(EMMessage *)myMessage{
    
    
    if (_myMessage != myMessage) {
        [_myMessage release];
        _myMessage = [myMessage retain];
    }
    
    
    
    self.timeLabel.text = [LYSupportTools messageTimeWithTimestamp:_myMessage.timestamp];
    [self.timeLabel sizeToFit];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(0);
        make.centerX.mas_equalTo(self.contentView.mas_centerX);
        make.height.mas_equalTo(20);
        
    }];

    
    
    
    UIImage *image = [UIImage imageNamed:@"chatBubble_mask_vip_left"];
    
    // image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.6, image.size.width * 0.4, image.size.height * 0.3, image.size.width * 0.4)];
    
    //image的拉伸效果
    image = [image stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    
    self.textImageView.image = image;
    self.voiceImageView.image = image;
    self.videoImageView.image = image;
    
    
    //知道发送信息类型
    id bodyClass = [_myMessage.messageBodies lastObject];
    
    
    //如果是文本类型
    if ([bodyClass isKindOfClass:[EMTextMessageBody class]]) {
        
        self.playImage.hidden = YES;
        self.voiceImageView.hidden = YES;
        self.videoImageView.hidden = YES;
        self.textImageView.hidden = NO;
        
        EMTextMessageBody *textBody = bodyClass;
        self.messageLabel.text = textBody.text;
        NSLog(@"%@",textBody.text);
/*
        //自适应高度(类目)
        CGFloat height = [[self class] heightForCellWithSizeWidth:LabelMaxWidth withString:textBody.text withLabelFont:17];
        
        // uilabel 类目
        [self.messageLabel autoLabelWithHeight:height];
*/

           [self attributesTextMessage]; 
    
        
        //如果是图片类型
    }else if ([bodyClass isKindOfClass:[EMImageMessageBody class]]){
    
        self.playImage.hidden = YES;
        self.textImageView.hidden = YES;
        self.voiceImageView.hidden = YES;
        self.videoImageView.hidden = NO;
        
       self.messageLabel.attributedText = [self attributesImageMessage];
    
    
    //如果是语音类型
     }else if ([bodyClass isKindOfClass:[EMVoiceMessageBody class]]){
    
         self.playImage.hidden = YES;
         self.textImageView.hidden = YES;
         self.videoImageView.hidden = YES;
         self.voiceImageView.hidden = NO;
         
    self.messageLabel.attributedText = [self attributesVoiceMessage];
    
    
   
         
    }else if ([bodyClass isKindOfClass:[EMVideoMessageBody class]]){
        
        self.textImageView.hidden = YES;
        self.playImage.hidden = NO;
        self.voiceImageView.hidden = YES;
        self.videoImageView.hidden = NO;
        
         self.messageLabel.attributedText = [self attributesVideoMessage];
         
    }else if ([bodyClass isKindOfClass:[EMLocationMessageBody class]]){
        
        self.textImageView.hidden = YES;
        self.playImage.hidden = YES;
        self.voiceImageView.hidden = YES;
        self.videoImageView.hidden = NO;
        
        self.messageLabel.attributedText = [self attributeslocationMessage];
        
    }
    
    
  //约束messageLabel
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(30);
        make.left.mas_equalTo(70);
        
        
    }];
    

    //限制label最宽的宽度是多少
    self.messageLabel.preferredMaxLayoutWidth = LabelMaxWidth;
    
    
 
    //约束textImageView
    [self.textImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.edges.equalTo(self.messageLabel).mas_equalTo(UIEdgeInsetsMake(-5, -15, 10, -10));
        
        
    }];
    
    
    
    
    //约束voiceImageView
    [self.voiceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.edges.equalTo(self.messageLabel).mas_equalTo(UIEdgeInsetsMake(0, -5, 0, -10));
        
    }];
    
    //约束videoImageView
    [self.videoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.edges.equalTo(self.messageLabel).mas_equalTo(UIEdgeInsetsMake(-5, - 10, -5, -5));
        
        
    }];
    







}


+(CGFloat)heightOfCellWithtextMessge:(EMTextMessageBody *)message{
    CGFloat height = 0;
    
    NSMutableAttributedString *attStr = [LYSupportTools emotionStrWithString:message.text];
    
    //计算字体大小
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, attStr.length)];
    
    CGSize textSize = [attStr boundingRectWithSize:CGSizeMake(LabelMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    height = textSize.height + 40;
    
    //如果高度小于60就不能再小了
    if (height < 80) {
        height = 80;
    }
    return height;
    
    
}





-(void)messageLabelTap:(UITapGestureRecognizer *)tap{
    
    
    NSLog(@"用于播放语音");
    
    //只有当前的类型是语音的时候才能播放
    //获得消息体
    id bodyClass = self.myMessage.messageBodies[0];
    
    if ([bodyClass isKindOfClass:[EMVoiceMessageBody class]]) {
        NSLog(@"播放语音");
        
        [self tapToPlayVoice];
        
    }else if ([bodyClass isKindOfClass:[EMImageMessageBody class]]){
        NSLog(@"显示原图");
        
        [self showOriginalImage];
        
        
    }else if ([bodyClass isKindOfClass:[EMVideoMessageBody class]]){
        
        [self playVideo];
        
    }else if ([bodyClass isKindOfClass:[EMLocationMessageBody class]]){
        
        LocationViewController *location = [[LocationViewController alloc]init];
        [[self viewController].navigationController pushViewController:location animated:YES];
        [location release];
        
    }
    
}


#pragma mark -- 返回表情text
-(void)attributesTextMessage{
    
    EMTextMessageBody *body = self.myMessage.messageBodies[0];
    
    
    
    NSMutableAttributedString *attStr = [LYSupportTools emotionStrWithString:body.text];
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, attStr.length)];
    
    // CGSize textSize = [attStr boundingRectWithSize:CGSizeMake(LabelMaxWidth,CGFLOAT_MAX ) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    self.messageLabel.attributedText = attStr;
    
    
}






#pragma mark --返回语音富文本
-(NSAttributedString *)attributesVoiceMessage{
    
    //创建一个可变的富文本
    NSMutableAttributedString *voiceAtt = [[NSMutableAttributedString alloc]init];
    
    
    
    //发送方: 富文本 = 时间 + 图片
    //拼接时间
    //获取时间
    
    
    
    //    拼接图片
    UIImage *bgImage = [UIImage imageNamed:@"messages_audio_animation_fromfull"];
    
    //    创建图片附件
    NSTextAttachment *imageText = [[NSTextAttachment alloc]init];
    
    imageText.image = bgImage;
    imageText.bounds = CGRectMake(0, -10, 30, 30);
    
    
    //    创建图片富文本
    NSAttributedString *imageAtt = [NSAttributedString attributedStringWithAttachment:imageText];
    [imageText release];
    
    //    添加图片富文本
    [voiceAtt appendAttributedString:imageAtt];
    
    
    
    //获取语音body
    EMVideoMessageBody *voiceBody = self.myMessage.messageBodies[0];
    //获取语音时长
    NSInteger duration = voiceBody.duration;
    
    NSLog(@"%ld",duration);
    
    NSInteger count = duration;
    if (count > 4) {
        count = 4;
    }
    
    NSLog(@"%ld",count);
    
    NSMutableString *spaceString = [NSMutableString stringWithString:@" "];
    for (int i = 0; i < count; i++) {
        
        [spaceString appendString:spaceString];
    }
    
    
    
    
    //拼接语音时长
    NSString *timeString = [NSString stringWithFormat:@"%@%ld\"",spaceString,duration];
    //创建时间的富文本
    NSAttributedString *timeAtt = [[NSAttributedString alloc]initWithString:timeString];
    
    
    
    
    [voiceAtt appendAttributedString:timeAtt];
    [timeAtt release];
    
  
    
   
    return [voiceAtt copy];
    
    
    
}


#pragma mark -- 轻拍播放语音
-(void)tapToPlayVoice{

    //判断播放状态
    BOOL playStatus= [EMAudioPlayerUtil isPlaying];
    
    if (playStatus) {
        NSLog(@"正在播放");
        
        //获得正在播放的语音路径 返回一个wav格式的字符串
        NSString *playingPath = [EMAudioPlayerUtil playingFilePath];
        //获得当前轻拍的语音路径   封装一个返回wav的字符串
        NSString *touchPath = [LYVoiceMessageShowTool touchingPathFileWithTouchMessage:self.myMessage];
        
        
        //判断是否相等,(如果不等,证明点击的是别的语音,直接进行播放新的)
        
        if (![playingPath isEqualToString:touchPath]) {
            
            [LYVoiceMessageShowTool playWithMessage:self.myMessage withMessageLabel:self.messageLabel receiver:YES];
            
        }else{
            //如果相等,证明点击的是同一个,代表我要停止
            
            //再次点击时停止播放
            [EMAudioPlayerUtil stopCurrentPlaying];
            //停止动画
            [LYVoiceMessageShowTool stopAnimatingImage];
            
            
        }
        
        
    }else{
        
        NSLog(@"没有播放");
        //正常播放
        [LYVoiceMessageShowTool playWithMessage:self.myMessage withMessageLabel:self.messageLabel receiver:YES];
        
        NSLog(@"声音启动");
    }
    


    
    
    
}



#pragma mark --返回图片富文本
-(NSAttributedString *)attributesImageMessage{
    
    
    EMImageMessageBody *imageBody = self.myMessage.messageBodies[0];
    
    
    
    
    CGRect thumbnailImageFrame = CGRectMake(0, 0, imageBody.thumbnailSize.width * 1.5 , imageBody.thumbnailSize.height * 1.5);
    
    NSTextAttachment *imageText = [[NSTextAttachment alloc]init];
    imageText.bounds = thumbnailImageFrame;
    
    NSFileManager *manager = [NSFileManager defaultManager];
    //如果本地图片存在,直接从本地显示图片
    if ([manager fileExistsAtPath:imageBody.thumbnailLocalPath]) {
        
        UIImage *image = [UIImage imageWithContentsOfFile:imageBody.thumbnailLocalPath];
        
        NSLog(@"%@",imageBody.thumbnailLocalPath);
        
        imageText.image = image;
        
        
        NSLog(@"本地图片");
        
    }else{
        
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageBody.thumbnailRemotePath]];
        UIImage *image = [UIImage imageWithData:imageData];
        imageText.image = image;
        
        NSLog(@"网路图片");
    }
    
    
    NSAttributedString *imageAtt = [NSAttributedString attributedStringWithAttachment:imageText];
    
    [imageText release];
    
    
    return imageAtt;
    
    
}




#pragma mark -- 找到cell的控制器
-(UIViewController *)viewController{
    
    for (UIView *next = [self superview]; next; next = [next superview]) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            
            return (UIViewController *)nextResponder;
        }
    }
    
    return nil;
    
    
}

#pragma mark -- 显示全屏图
-(void)showOriginalImage{
    
    
    EMImageMessageBody *imageBody = self.myMessage.messageBodies[0];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    
    UIImage *bigImage = [[UIImage alloc]init];
    
    //如果本地图片存在,直接从本地显示图片
    if ([manager fileExistsAtPath:imageBody.localPath]) {
        
        UIImage *image = [UIImage imageWithContentsOfFile:imageBody.localPath];
        
        NSLog(@"%@",imageBody.localPath);
        
        bigImage = image;
        
        NSLog(@"本地图片");
        
    }else{
        
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageBody.remotePath]];
        UIImage *image = [UIImage imageWithData:imageData];
        bigImage = image;
        
        NSLog(@"网路图片");
    }
    
    
    
    
    
    //按比例缩放
    UIGraphicsBeginImageContextWithOptions(bigImage.size, YES, 0);
    // thumb  = UIGraphicsGetImageFromCurrentImageContext();
    //   UIGraphicsEndImageContext();
    
    UIImageView *originalImageView = [[UIImageView alloc] initWithImage:bigImage];
    
    
    //背景View
    BaseView *bgView = [[BaseView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    
    bgView.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [self viewController].navigationController.navigationBarHidden = YES;
    [[self viewController].view addSubview:bgView];
    bgView.tag = 100001;
    
    
    [bgView release];
    
    [bgView addSubview:originalImageView];
    
    originalImageView.tag = 11111;
    [originalImageView release];
    
    
    CGFloat w = [UIScreen mainScreen].bounds.size.width;
    CGFloat h = w / originalImageView.bounds.size.width * originalImageView.bounds.size.height;
    
    
    originalImageView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - w) * 0.5, ([UIScreen mainScreen].bounds.size.height - h) * 0.5, w, h);
    
    UITapGestureRecognizer *removeOriginalViewTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeOriginalViewTap:)];
    
    [bgView addGestureRecognizer:removeOriginalViewTap];
    
    [removeOriginalViewTap release];
    
    
}

#pragma mark -- 移除全屏图
-(void)removeOriginalViewTap:(UITapGestureRecognizer *)tap{
    NSLog(@"走了");
    BaseView *isView = [[self viewController].view viewWithTag:100001];
    
    [isView removeFromSuperview];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    [self viewController].navigationController.navigationBarHidden = NO;
    
    
}


#pragma mark --返回视频富文本
-(NSAttributedString *)attributesVideoMessage{
    
    
    EMVideoMessageBody *videoBody = self.myMessage.messageBodies[0];
    NSLog(@"%ld",videoBody.duration);
    NSLog(@"%.2f",videoBody.size.width);
    NSLog(@"%.2f",videoBody.size.height);
    
    //       CGRect thumbnailImageFrame = CGRectMake(0, 0, videoBody.thumbnailSize.width * 0.5, imageBody.thumbnailSize.height * 0.5);
    
    NSTextAttachment *imageText = [[NSTextAttachment alloc]init];
    //    imageText.bounds = thumbnailImageFrame;
    
    NSFileManager *manager = [NSFileManager defaultManager];
    //如果本地图片存在,直接从本地显示图片
    if ([manager fileExistsAtPath:videoBody.thumbnailLocalPath]) {
        
        NSLog(@"%@",videoBody.thumbnailLocalPath);
        
        UIImage *image = [UIImage imageWithContentsOfFile:videoBody.thumbnailLocalPath];
        
        
        NSLog(@"%@",videoBody.thumbnailLocalPath);
        
        imageText.image = image;
        imageText.bounds = CGRectMake(0, 0, image.size.width * 1.5, image.size.height *1.5);
        
        NSLog(@"本地视频缩略图");
        
    }else{
        
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoBody.thumbnailRemotePath]];
        UIImage *image = [UIImage imageWithData:imageData];
        imageText.image = image;
        imageText.bounds = CGRectMake(0, 0, image.size.width * 1.5, image.size.height * 1.5);
        NSLog(@"网路视频缩略图");
    }
    
    
    NSAttributedString *imageAtt = [NSAttributedString attributedStringWithAttachment:imageText];
    
    [imageText release];
    
    
    return imageAtt;
    
    
}

#pragma mark -- 播放视频
-(void)playVideo{
    
    [self downloadVideo];
    
    EMVideoMessageBody *videoBody = self.myMessage.messageBodies[0];
    
    NSLog(@"%@",videoBody.localPath);
    NSURL *newUrl = [NSURL fileURLWithPath:videoBody.localPath];
    
    
    NSLog(@"%@",newUrl);
    

}


-(void)downloadVideo{
    
    EMVideoMessageBody *videoBody = self.myMessage.messageBodies[0];

    NSString *urlString = videoBody.remotePath;
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSessionConfiguration *configu = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configu delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self viewController].view animated:YES];
    hud.labelText = @"正在下载";
    
    
    [task resume];
    
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    [MBProgressHUD hideHUDForView:[self viewController].view animated:YES];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    

    
    NSString *videoPath = [filePath stringByAppendingPathComponent:@".mp4"];
    
    NSLog(@"%@",videoPath);
    
    NSFileManager  *manager = [NSFileManager defaultManager];
    
    [manager moveItemAtPath:location.path toPath:videoPath error:nil];
    
    NSURL *videoUrl = [NSURL fileURLWithPath:videoPath];
    
    NSLog(@"%@",videoUrl);
    
    //初始化
    AVPlayerViewController *playerView = [[AVPlayerViewController alloc]init];
    
    //AVPlayerItem 视频的一些信息  创建AVPlayer使用的
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:videoUrl];
    
    //通过AVPlayerItem创建AVPlayer
    AVPlayer  *player = [[AVPlayer alloc]initWithPlayerItem:item];
    [item release];
    
    //设置AVPlayerViewController内部的AVPlayer为刚创建的AVPlayer
    playerView.player = player;
    [player release];
    
    playerView.view.frame = [UIScreen mainScreen].bounds;
    
    
    [[self viewController] presentViewController:playerView animated:YES completion:nil];
    [playerView release];
    

    [manager removeItemAtPath:videoPath error:nil];
    
    
}


#pragma mark -- 地图消息的富文本
-(NSAttributedString *)attributeslocationMessage{
    
    //    EMLocationMessageBody *location = self.myMessage.messageBodies[0];
    
    NSTextAttachment *imageText = [[NSTextAttachment alloc]init];
    
    imageText.image = [UIImage imageNamed:@"location_"];
    
    imageText.bounds = CGRectMake(0, 0, 80, 80);
    
    NSAttributedString *attStr = [NSAttributedString attributedStringWithAttachment:imageText];
    
    return attStr;
    
    
}


@end
